package com.inspur.gs.sbssdl.sbwhgl.sbrh.sbrh.back.commoncmps;

import com.inspur.edp.bef.core.LcpUtil;
import com.inspur.edp.caf.db.dbaccess.DbParameter;
import com.inspur.edp.caf.db.dbaccess.DynamicResultRow;
import com.inspur.edp.caf.db.dbaccess.IConverToListFunc;
import com.inspur.edp.caf.db.dbaccess.IDbParameter;
import com.inspur.edp.cef.entity.changeset.ModifyChangeDetail;
import com.inspur.edp.cef.entity.entity.IEntityData;
import com.inspur.edp.dxc.common.domain.CommonResult;
import com.inspur.edp.dxc.spi.components.BaseBeforeDBUpdateComponent;
import com.inspur.edp.qdp.bql.api.IBqlExecuter;
import com.inspur.edp.qdp.bql.api.OptionType;
import io.iec.edp.caf.runtime.config.BqlBeanUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

public class SbssSbrhBzDatabaseBefore extends BaseBeforeDBUpdateComponent {

    private final IBqlExecuter bqlExe = BqlBeanUtil.getAppCtx().getBean(IBqlExecuter.class);

    String selectSql = "select ID, DEVCLASS, DEVSPEC, LUFATNAME, LUITEM, LUMECH, LUMODE, NOTE,CYCLETYPE,CYCLELABEL, CYCLEVALUE from SBSS_SBRH_STAND\n" +
            "where DEVCLASS = :devClass and DEVSPEC = :devSpec and LUMECH = :luMech and LUITEM = :luItem";

    public void DataBaseImportBefore() {
        List<ModifyChangeDetail> details = super.getDetails();
        bqlExe.getOptions().setOptionType(OptionType.ExecuteSql);

        List<ModifyChangeDetail> collect = details.stream().filter(this::coverStand)
                .collect(Collectors.toList());

        CommonResult result = super.getResult();
        result.setChangeDetails(collect);
    }


    // 覆盖同名标准
    private boolean coverStand(ModifyChangeDetail detail) {
        //设备大类、小类、润滑机构、部件
        String[] paramString = {"devClass", "devSpec", "luMech", "luItem"};

        // 比较库内相同属性
        List<IDbParameter> params = new ArrayList<>();
        for (String ps : paramString) {
            Object item = detail.getItem(ps);
            // 任意属性为空则丢弃该数据
            if (item == null) {
                return false;
            }
            params.add(new DbParameter(ps, item));
        }

        List<DynamicResultRow> resultRows = bqlExe.executeSelectStatement(selectSql, new ArrayList<>(), params.toArray(new IDbParameter[]{}));

        // 标准不存在，则不覆盖
        if (resultRows.isEmpty()) {
            return true;
        }

        HashMap<String, Object> detailChanges = detail.getPropertyChanges();

        // 循环遍历数据,不保证数据唯一,给自己留条后路
        for (DynamicResultRow row : resultRows) {
            HashMap<String, Object> standMap = new HashMap<>(detailChanges);
            standMap.put("id", row.get("id"));

            StringBuilder updateSql = new StringBuilder("update SBSS_SBRH_STAND set ");
            List<IDbParameter> upParams = new ArrayList<>();
            standMap.forEach((k, v) -> {
                if (!k.equals("ID")) {
                    if (v != null){
                        updateSql.append(k).append(" = :").append(k).append(",");
                        upParams.add(new DbParameter(k, v));
                    }
                }
            });
            updateSql.deleteCharAt(updateSql.length() - 1);
            updateSql.append(" where ID = :ID");
            upParams.add(new DbParameter("ID", standMap.get("id")));
            bqlExe.executeBqlStatement(updateSql.toString(), new ArrayList<>(), upParams.toArray(new IDbParameter[]{}));
        }

        // 更新数据则无需更新
        return false;
    }


}